import { ReactElement, useState, useEffect, useRef } from 'react'
import { Space, Radio, Button, message, Modal } from 'antd'
import { useLocation } from 'react-router-dom'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import style from './index.module.less'
import Search, { formatCondition } from '@src/pages/admin/components/searchForm'
import Table, { TableRef } from '@src/components/table'
import { ConditionSchema } from '@src/components/schema/condition'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import { getCaseListRequest } from './ajax'
import { formatDate } from '@js/tool'
import qs from 'query-string'
import { json2Excel } from '@js/excel'
import InputModal from './components/inputModal'
import CopyModal from './components/copyModal'
import { useDispatch } from 'react-redux'
import { addWindow } from '@src/redux/actions/tab'

const { confirm } = Modal

// 初始化数据
async function initData (data: { [k: string]: any}, setDataSource: (v: CaseSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseListRequest({
    condition: formatAllCondition(data),
    page: data.page,
    limit: data.limit
  }))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
  }
}

// 格式化搜索条件
function formatAllCondition (o: { [k: string]: any }): ConditionSchema[] {
  const condition = formatCondition(o)
  if (typeof o.status === 'string') {
    condition.push({ k: 'score_status', o: '=', v: o.status })
  }
  return condition
}

// 下载excel二次确认
function confirmDownload (data: { [k: string]: any}, total: number): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要导出excel吗？',
    onOk () {
      downloadExcel(data, total).catch(e => console.error(e))
    }
  })
}

async function downloadExcel (data: { [k: string]: any}, total: number): Promise<void> {
  const hide = message.loading('下载中', 120)
  const [e, d] = await awaitWrap(getCaseListRequest({
    condition: formatAllCondition(data),
    page: 1,
    limit: total
  }))
  hide()
  if (e === null && d !== null) {
    const list: Array<{ [k: string]: any }> = d.list.map(li => {
      return {
        仲裁程序: li.procedure,
        办案秘书: li.processer,
        受理秘书: li.accepter,
        收案理日期: formatDate(li.accept_datetime, 'YYYY-MM-DD'),
        标的: li.dispute_amount,
        反请求标的: li.counter_dispute_amount,
        案号: li.caseno_desc,
        案由: li.cause_action,
        '独任/首席仲裁员': li.arbitrator,
        申请人: li.applicant_name,
        申请人仲裁员: li.arbitrator1,
        移交办案日期: formatDate(li.to_process_datetime, 'YYYY-MM-DD'),
        立案日期: formatDate(li.docket_datetime, 'YYYY-MM-DD'),
        组庭日期: formatDate(li.arbitrator_assign_datetime, 'YYYY-MM-DD'),
        结案方式: li.closure_type,
        结案文书报送日期: formatDate(li.closure_report_datetime, 'YYYY-MM-DD'),
        结案文书签批日期: formatDate(li.closure_audit_datetime, 'YYYY-MM-DD'),
        结案文书送达完成日期: formatDate(li.closure_datetime, 'YYYY-MM-DD'),
        归档日期: formatDate(li.file_datetime, 'YYYY-MM-DD'),
        被申请人: li.respondent_name,
        被申请人仲裁员: li.arbitrator2
      }
    })
    json2Excel([{ data: list, sheetname: '案件列表' }], '案件列表')
  }
}

interface Props {
  meta: {
    params: {[k: string]: any}
  }
}

function Main ({ meta = {params: {}} }: Props): ReactElement {
  const dispatch = useDispatch()
  const tableRef = useRef<TableRef>(null)
  const [status, setStatus] = useState<string | undefined>()
  const [dataSource, setDataSource] = useState<CaseSchema[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [searchData, setSearchData] = useState<{[k: string]: any}>({})
  const [visible, setVisible] = useState(false)
  const [copyCase, setCopyCase] = useState<CaseSchema | null>(null)
  const [copyVisible, setCopyVisible] = useState(false)
  const [params, setParams] = useState<{[k: string]: any}>(qs.parse(qs.stringify(meta.params)))
  useEffect(() => {
    const s = params.status
    if ((typeof s === 'string' || s === undefined) && s !== status) {
      setStatus(s)
    }
  }, [params])
  useEffect(() => {
    if (meta.params instanceof Object) {
      setParams(qs.parse(qs.stringify(meta.params)))
    }
  }, [meta])
  return (
    <div className={style.container}>
      <InputModal visible={visible} hide={() => setVisible(false)} refreshData={() => tableRef.current?.refreshData()} />
      <CopyModal visible={copyVisible} data={copyCase} hide={() => { setCopyCase(null); setCopyVisible(false) }} refreshData={() => tableRef.current?.refreshData()} />
      <Search unused={['assign_datetime', 'begin_datetime']} params={params} setParams={setParams} />
      <div className={style.table}>
        <div className={style['operate-line']}>
          <span className={style['operate-title']}>案件列表</span>
          <Space size={12}>
            <Radio.Group value={status} onChange={e => setParams({ ...params, status: e.target.value, page: 1 })}>
              <Radio.Button>全部</Radio.Button>
              <Radio.Button value='未确认'>未确认</Radio.Button>
              <Radio.Button value='已确认'>确认信息</Radio.Button>
              <Radio.Button value='抽查中'>抽查中</Radio.Button>
              <Radio.Button value='已抽查'>已录抽查</Radio.Button>
            </Radio.Group>
            <Button type='primary' ghost onClick={() => confirmDownload(searchData, total)} >导出excel</Button>
            <Button onClick={() => setVisible(true)} >新建案件</Button>
            <Button type='primary' onClick={() => { dispatch(addWindow({ id: 'CaseInputBatch', componentName: 'CaseInputBatch', title: '批量导入案件' })) }} >批量导入案件</Button>
          </Space>
        </div>
        <Table ref={tableRef} columns={getColumn(dispatch, setCopyCase, setCopyVisible)} params={params} setParams={setParams} loading={loading} total={total} dataSource={dataSource} onChange={async (d: any) => {
          setSearchData(d)
          await initData(d, setDataSource, setTotal, setLoading)
        }} />
      </div>
    </div>
  )
}

export default Main
